<?php

namespace App\Http\Controllers\Admin\Maintain;

use App\Http\Controllers\AdminController;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class DatabaseController extends AdminController
{
    private const CACHE_KEY = 'databases_all';
    public function data(Request $request)
    {
        $data = $this->getCacheData();
        if ($keywords = $request->get('keywords')) {
            $data = $data->filter(function ($item) use ($keywords) {
                return str_contains($item['name'], $keywords);
            });
        }
        $list = $data->all();
        return $this->succeed($list);
    }

    public function show(Request $request)
    {
        $data = [];
        if ($table = $request->get('table')) {
            $data = Cache::remember('SHOW_FULL_COLUMNS_FROM_'.$table, Carbon::now()->addMinutes(5), function () use ($table) {
                return get_object_vars((object)DB::select(sprintf('SHOW FULL COLUMNS FROM `%s`', $table)));
            });
        }
        return $this->succeed($data);
    }

    public function optimize(Request $request)
    {
        $request->validate(['table' => 'required|array']);
        $tables = implode('`,`', $request->get('tables'));
        DB::statement(sprintf('OPTIMIZE TABLE `%s`', $tables));
        $this->createSyslog('优化了数据表', ['tables' => $tables]);
        return $this->succeed();
    }

    public function repair(Request $request)
    {
        $request->validate(['table' => 'required|array']);
        $tables = implode('`,`', $request->get('tables'));
        DB::statement(sprintf('REPAIR TABLE `%s`', $tables));
        $this->createSyslog('修复了数据表', ['tables' => $tables]);
        return $this->succeed();
    }

    public function clear(Request $request)
    {
        $request->validate(['table' => 'required']);
        $table = $request->get('table');
        DB::statement(sprintf('TRUNCATE TABLE `%s`', $table));
        $this->createSyslog('清空了数据表', ['table' => $table]);
        return $this->succeed();
    }

    public function destroy(Request $request)
    {
        $request->validate(['table' => 'required']);
        $table = filterStr($request->get('table'));
        DB::statement(sprintf('DROP TABLE `%s`', $table));
        $this->delCache();
        $this->createSyslog('删除了数据表', $table);
        return $this->succeed();
    }

    private function getCacheData()
    {
        return Cache::remember('SHOW_TABLE_STATUS', Carbon::now()->addMinutes(20), function () {
            return collect(get_object_vars((object)DB::select('SHOW TABLE STATUS')));
        });
    }

    private function delCache()
    {
        Cache::forget(self::CACHE_KEY);
    }
}
